﻿using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.Entities;

namespace Sustainalytics.Governance.Service
{
    public static class GovernanceClaimsCheckerExtensions
    {

        public static bool ValidateGovernanceClaim(this IClaimsChecker claimsChecker, ApiController controller)
        {
            if (claimsChecker.Validate(controller, null))
                return true;
            
            return false;
        }


        public static bool Validate(this IClaimsChecker claimsChecker, ApiController ctrl, List<ResourceParameters> parameters)
        {
            // get current principal
            var principal = (ClaimsPrincipal)ctrl.User;

            // get route prefix
            object[] attrs = ctrl.GetType().GetCustomAttributes(typeof(RoutePrefixAttribute), false);
            RoutePrefixAttribute routePrefixAttrs = attrs == null || attrs.Length == 0 ? null : attrs.Select(a => (RoutePrefixAttribute)a).FirstOrDefault();

            // get HTTP Method
            string httpMethod = ctrl.Request.Method.Method;

            bool valid = claimsChecker.Validate(
                claimsPrincipal: principal,
                resource: routePrefixAttrs == null ? null : routePrefixAttrs.Prefix,
                verb: httpMethod,
                parameters: parameters);

            return valid;
        }
    }
}

